<template>
  <div v-loading="loading" class="parentStyle">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <div class="area-header">
        <span class="area-header-title">{{ $t('基本信息') }}</span>
      </div>
      <div class="el-row">
        <el-row>
          <el-col v-if="form.dealType !== 'bond'" :span="12" :style="{ height: Wheight }">
            <el-form-item :label="$t('公司名称')" prop="company.companyName">
              <span slot="label"> {{ $t(companyLabel) }} </span>
              <el-autocomplete
                v-model="form.company.companyName"
                class="inline-input"
                :fetch-suggestions="companyQuerySearch"
                :placeholder="$t(companyLabel)"
                :trigger-on-focus="false"
                :maxlength="100"
                @select="companyHandleSelect"
                @change="findDealListByCompanyName({ value: $event, id: undefined })"
              >
                <template v-if="form.id" slot="append" @click="companyHandleSelect">
                  <router-link
                    target="_blank"
                    :to="{path:'/company/base/companyBaseHome',query:{companyId:form.companyId}}"
                    class="link_a"
                  >{{ $t('查看标的公司信息') }}</router-link>
                </template>
              </el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col v-if="form.dealType !== 'bond'" :span="12" :style="{height: Wheight}">
            <el-form-item :label="$t('项目名称')" prop="dealName">
              <el-input v-if="!form.id" v-model="form.dealName" :placeholder="$t('项目名称')" show-word-limit :maxlength="100" @change="checkDealNameExist()" />
              <el-input v-else v-model="form.dealName" show-word-limit :maxlength="100" @change="checkDealNameExist()">
                <template v-if="form.id" slot="append">
                  <span @click="chartOpenHandle">{{ $t('查看投资架构图') }}</span>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <!-- 债券项目不需要公司名称 -->
          <el-col v-if="form.dealType === 'bond'" :span="12" :style="{height: Wheight}">
            <el-form-item :label="$t('项目名称')" prop="dealName">
              <el-input v-model="form.dealName" :placeholder="$t('项目名称')" show-word-limit :maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('项目负责人')" prop="personCharge">
              <UserSelect
                v-model="form.personCharge"
                :placeholder="$t('项目负责人')"
                @change="personChargeChange($event)"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('项目类型')" prop="dealType">
              <dictSelect
                v-model="form.dealType"
                :disabled="(form.dealType !== undefined && form.id !== undefined) || !dealTypeUpdate"
                dictionary="deal_type"
                @change="dealTypeChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('关注等级')" prop="levelConcern">
              <el-select v-model="form.levelConcern" :placeholder="$t('关注等级')" clearable>
                <el-option
                  v-for="dict in levelConcernOptions"
                  :key="dict.dictValue"
                  :label="$t(dict.dictLabel)"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('项目状态')" prop="dealStatus">
              <dictSelect
                v-model="form.dealStatus"
                dictionary="deal_status"
                :disabled="dealStatusModify"
                @change="dealStatusChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('初次接触时间')" prop="dateTouchFirst">
              <DatePicker v-model="form.dateTouchFirst" :placeholder="$t('初次接触时间')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('预计投资时间')" prop="dateInvestmentEstimate">
              <DatePicker v-model="form.dateInvestmentEstimate" :placeholder="$t('预计投资时间')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('预计投资金额') + $t('金额单位')" prop="amountInvestmentEstimate">
              <Money v-model="form.amountInvestmentEstimate" unit="w" :placeholder="$t('预计投资金额')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('投资币种')" prop="currency">
              <el-select v-model="form.currency" :placeholder="$t('投资币种')">
                <el-option
                  v-for="dict in currencyOptions"
                  :key="dict.dictValue"
                  :label="$t(dict.dictLabel)"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('项目来源')" prop="dealSource">
              <!-- <el-select v-model="form.dealSource" :placeholder="$t('项目来源')">
              <el-option
                v-for="dict in dealSourceOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select> -->
              <el-input v-model="form.dealSource" :placeholder="$t('项目来源')" show-word-limit :maxlength="100" />
            </el-form-item>
          </el-col>
          <!--        <el-col v-show="form.dealSource !== '' && (form.dealSource === 'NBTJ' || form.dealSource === 'WBTJ')" :span="12">-->
          <el-col :span="12">
            <el-form-item :label="$t('推荐人')" prop="sourceName">
              <el-input v-model="form.sourceName" :placeholder="$t('推荐人')" show-word-limit :maxlength="100" />
            </el-form-item>
          </el-col>
        </el-row>
        <!--股权投资字段-->
        <dealBaseEquityForm v-if="form.dealType !== 'debt' && form.dealType !== 'bf' && form.dealType !== 'estate' && form.dealType !== 'property' && form.dealType !== 'bond' && form.dealBaseEquity !== null" ref="dealBaseEquityForm" :equity-form="form.dealBaseEquity" />
        <!--债权投资字段-->
        <dealBaseDebtForm v-if="form.dealType === 'debt' && form.dealBaseDebt !== null" ref="dealBaseDebtForm" :equity-form="form.dealBaseDebt" />
        <!--参股基金字段-->
        <bfBaseForm v-if="form.dealType === 'bf' && form.bfBase !== null" ref="bfBaseForm" :bf-form="form.bfBase" />
        <!-- 地产基本信息字段-->
        <dealBaseEstateForm v-if="form.dealType === 'estate' && form.dealBaseEstate !== null" ref="dealBaseEstateForm" :estate-form="form.dealBaseEstate" />
        <!-- 持有型业务 -->
        <dealBasePropertyForm v-if="form.dealType === 'property' && form.dealBaseProperty !== null" ref="dealBaseProperty" :property-form="form.dealBaseProperty" />
        <!-- 债券投资 -->
        <dealBaseBondForm v-if="form.dealType === 'bond' && form.dealBaseBond !== null" ref="dealBaseBondForm" :bond-form="form.dealBaseBond" :other-btn-hide="btnHide" />
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('项目简介')" prop="dealIntroduction">
              <el-input v-model="form.dealIntroduction" type="textarea" :placeholder="$t('项目简介')" show-word-limit :maxlength="2000" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.dealStatus ==='ZZ'" :span="24">
            <el-form-item :label="$t('终止原因')" prop="terminationReason">
              <el-input v-model="form.terminationReason" type="textarea" :placeholder="$t('终止原因')" show-word-limit :maxlength="2000" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('项目主要优点')" prop="dealStrongPoint">
              <el-input v-model="form.dealStrongPoint" type="textarea" :placeholder="$t('项目主要优点')" show-word-limit :maxlength="2000" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('项目主要顾虑')" prop="dealScruple">
              <el-input v-model="form.dealScruple" type="textarea" :placeholder="$t('项目主要顾虑')" show-word-limit :maxlength="2000" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('交易细节')" prop="transactionDetails">
              <el-input v-model="form.transactionDetails" type="textarea" :placeholder="$t('交易细节')" show-word-limit :maxlength="2000" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('备注')" prop="remark">
              <el-input v-model="form.remark" type="textarea" :placeholder="$t('备注')" show-word-limit :maxlength="2000" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 团队成员 -->
      <div v-if="form.id === undefined" class="area-header" style="margin-top: 15px;">
        <span class="area-header-title">{{ $t('团队成员') }}</span>
      </div>
      <div v-if="form.id === undefined" style="margin-top:15px;">
        <el-table :data="form.dealTeamList" border class="nowrapTable formTable">
          <el-table-column :label="$t('序号')" align="center" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('用户名称')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('用户名称') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'dealTeamList.' + scope.$index + '.user.userId'" :rules="dealTeamListRules.userId">
                <UserSelect v-model="scope.row.user.userId" :disabled="scope.row.disabled" :placeholder="$t('选择用户')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('参与角色')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('参与角色') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'dealTeamList.' + scope.$index + '.role'" :rules="dealTeamListRules.role">
                <el-select v-model="scope.row.role" :disabled="scope.row.disabled && scope.row.role === 'F'" :placeholder="$t('参与角色')">
                  <el-option
                    v-for="dict in roleOptions"
                    :key="dict.dictValue"
                    :label="$t(dict.dictLabel)"
                    :value="dict.dictValue"
                    :disabled="dict.dictValue === 'F' || dict.dictLabel === '项目负责人'"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('备注')" align="center">
            <template slot="header" slot-scope="{}">
              <span>{{ $t('备注') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'dealTeamList.' + scope.$index + '.remark'">
                <el-input v-model="scope.row.remark" type="textarea" maxlength="2000" class="fileTextarea" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column v-if="!btnHide" :label="$t('操作')" align="center" width="60px">
            <template slot-scope="scope">
              <el-button v-hasPermi="['deal:dealbase:edit']" :disabled="scope.row.disabled" size="small" type="text" icon="el-icon-delete" @click="delTeam(scope.$index)" />
            </template>
          </el-table-column>
        </el-table>
        <div v-if="!btnHide" class="tol">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="addTeam()">{{ $t("添加") }}</el-button>
        </div>
      </div>

      <!-- 附件列表 -->
      <FileTable :list.sync="form.fileList" has-permi="deal:dealbase" data-type="deal_base" :business-type="form.dealType" :select-business-data="false" :btn-show="!otherBtnHide" />
    </el-form>

    <el-dialog :title="$t('')" :visible.sync="chartOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <invest-structure-chart ref="investStructureChart" :chart-data="chartData" :btn-list="btnList" />
    </el-dialog>

    <!-- 提醒设置 -->
    <el-dialog v-if="remindOpen" :title="$t('项目提醒')" :visible.sync="remindOpen" style="width: 66%;height: 78%;top: 10%;left: 14%;z-index: 2005;" :destroy-on-close="true" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <remindEvent ref="remindEvent" :has-permi="'deal:dealbase'" :is-show-deal-team="true" :is-show-role="true" :is-show-user="true" reminder-type="deal_base" />
    </el-dialog>

    <!-- 公司绑定对应的项目弹窗 -->
    <el-dialog :visible.sync="boundCompanyForm" :close-on-click-modal="false" :width="'60%'" :destroy-on-close="true" :modal="false" :lock-scroll="false" custom-class="monitorDialogForm" append-to-body>
      <div slot="title">
        <i class="el-icon-warning" style="color: orange;font-size: 15px;" />
        <span style="font-size: 15px;">{{ $t('当前公司在系统中已存在项目') }}</span>
      </div>
      <dealBaseBoundCompany ref="dealBaseBoundCompany" />
    </el-dialog>

    <div v-if="boundCompanyData.formOpen && !boundCompanyForm" class="right-company-div" @click="findDealListByCompanyName(boundCompanyData)">
      <el-tooltip :content="$t('当前公司在系统中已存在项目')">
        <i class="el-icon-d-arrow-left right-company-btn" style="line-height: 3.5;" />
      </el-tooltip>
    </div>

    <div v-show="!btnHide" slot="footer" class="dialog-footer">
      <SaveBtn has-permi="deal:dealbase" :cancel-show="openLocation === undefined" :bus-data="form" :cache-key="'deal_base_' + form.dealType">
        <template v-slot:middle>
          <el-button v-if="form.id" @click="openRemind">{{ $t('提醒') }}</el-button>
        </template>
      </SaveBtn>
    </div>
  </div>
</template>

<script>
    // 债权项目
    import dealBaseDebtForm from '@/views/deal/base/debt/dealBaseDebtForm'
    // 股权项目
    import dealBaseEquityForm from '@/views/deal/base/equity/dealBaseEquityForm'
    // 参股基金
    import bfBaseForm from '@/views/bf/base/bfBaseForm'
    // 地产项目
    import dealBaseEstateForm from '@/views/deal/base/estate/dealBaseEstateForm'
    // 债券项目
    import dealBaseBondForm from '@/views/deal/base/bond/dealBaseBondForm'
    // 持有型业务
    import dealBasePropertyForm from '@/views/deal/base/property/dealBasePropertyForm'
    // 天眼查接口选中后带出对应的项目
    import dealBaseBoundCompany from '@/views/deal/base/dealBaseBoundCompany.vue'
    // 项目提醒设置
    import remindEvent from '@/components/remind/sysRemindEvent.vue'
    import { saveDealBase, getDealBase, getDealBaseByName, findDealBroughtOutCompany } from '@/api/base/deal/dealBase'
    import { companyListByName, getCompanyBaseByName } from '@/api/company/base/companyBase'
    import investStructureChart from './investStructureChart'
    import { investChartData } from '@/api/fund/fundBase'
    import { saveDealInvestment } from '@/api/deal/investment/dealInvestment'

    export default {
        components: {
          remindEvent,
          dealBaseDebtForm,
          dealBaseEquityForm,
          bfBaseForm,
          investStructureChart,
          dealBaseEstateForm,
          dealBasePropertyForm,
          dealBaseBondForm,
          dealBaseBoundCompany
        },
        props: {
          dealBaseData: {
            type: Array,
            default: () => []
          },
          parameter: {
            type: Object,
            default: () => {}
          }
        },
        data() {
            return {
                otherBtnHide: false,
                loading: false,
                Wheight: '83px',
                // 公司名称label
                companyLabel: '公司名称',
                // 项目类型是否可以修改
                dealTypeUpdate: true,
                // 提醒设置
                remindOpen: false,
                // 表单参数
                form: {
                  bfBase: {
                    manageCompanyName: ''
                  },
                  company: {
                  },
                  dealBaseEstate: {
                    businessType: ''
                  },
                  dealBaseBond: {
                    primaryBondCategory: undefined,
                    secondaryBondCategory: undefined,
                    bondCode: undefined,
                    bondName: undefined,
                    financingSubject: undefined,
                    obligor: undefined,
                    countryRisk: undefined,
                    subjectName: undefined,
                    series: undefined,
                    nameCreditorRight: undefined,
                    fundManager: undefined,
                    fundSize: undefined,
                    termInvestment: undefined,
                    industryLevelOne: undefined,
                    industryLevelTwo: undefined,
                    currency: undefined,
                    dueDate: undefined,
                    repaymentOrder: undefined,
                    level: undefined,
                    structuredType: undefined,
                    bondType: undefined,
                    natureEnterprise: undefined,
                    externalRatingIssuer: undefined,
                    nameGuarantor: undefined,
                    ratingOutsideGuarantor: undefined,
                    thirdPartyPrincipal: undefined,
                    dealBaseBondLevelList: []
                  }
                  },
                  dealBaseProperty: {},
                // 项目状态是否可以修改
                dealStatusModify: false,
                // 是否隐藏保存等按钮
                btnHide: false,
                // 打开页面的位置，如果是通过项目home页面的路由打开，保存时不调用刷新list页面的方法
                openLocation: undefined,
                boundCompanyForm: false,
                boundCompanyData: {
                  formOpen: false,
                  value: undefined,
                  tycId: undefined
                },
                // 表单校验
                rules: {
                    dealName: [{ required: true, message: this.$t('必填信息'),	trigger: 'change' }, { whitespace: true, message: this.$t('不能为空'), trigger: 'blur' }],
                    dealType: [{ required: true, message: this.$t('必填信息'),	trigger: 'change' }],
                    personCharge: [{ required: true, message: this.$t('必填信息'),	trigger: 'change' }],
                    dealSource: [{ required: true, message: this.$t('必填信息'),	trigger: 'change' }],
                    'dealBaseEquity.industryFocus': [{ required: true, message: this.$t('必填信息'),	trigger: 'change' }],
                    dealStatus: [{ required: true, message: this.$t('必填信息'),	trigger: 'change' }],
                    terminationReason: [{ required: true, message: this.$t('必填信息'),	trigger: 'change' }],
                    'company.companyName': [{ required: true, message: this.$t('必填信息'),	trigger: 'change' }, { whitespace: true, message: this.$t('不能为空'), trigger: 'blur' }],
                    'bfBase.manageCompanyName': [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                    'dealBaseEstate.businessType': [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                    currency: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
                    // projectLocation: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                    // detailedAddress: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                    // propertyType: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                    // businessType: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
                },
                dealTeamListRules: {
                  userId: [{ required: true, message: this.$t('必填信息'),	trigger: 'change' }],
                  role: [{ required: true, message: this.$t('必填信息'),	trigger: 'change' }]
                },
                // 币种
                currencyOptions: [],
                // 项目类型
                dealTypeOptions: [],
                // 项目来源
                dealSourceOptions: [],
                // 关注等级
                levelConcernOptions: [],
                // 项目ID
                dealId: this.$route.query.id,
                // 天眼查查询条件
                tycParam: {
                  id: '',
                  companyName: '',
                  tycId: ''
                },
              chartOpen: false,
              chartData: {},
              // 参与角色 字典deal_team_role字典
              roleOptions: [],
              btnList: [
                {
                  name: '出资人',
                  type: 'investor',
                  color: 'rgba(183,221,232)'
                },
                {
                  name: 'GP',
                  type: 'gp',
                  color: 'rgba(254,229,153)'
                },
                {
                  name: '投资主体',
                  type: 'fund',
                  color: 'rgba(221,214,229)'
                },
                {
                  name: 'SPV',
                  type: 'spv',
                  color: 'rgba(215,227,191)'
                },
                {
                  name: '项目',
                  type: 'deal',
                  color: 'rgba(216,216,216)'
                }
              ]
            }
        },
        watch: {
          dealBaseData: function() {
              this.form = this.dealBaseData
          }
          // 'form.bfBase.manageCompanyName': {
          //   handler(val) {
          //     if (!val || val.trim() === '') {
          //       this.rules.manageCompanyName = [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
          //     } else {
          //       this.rules.manageCompanyName = [{ required: false, message: this.$t('必填信息'), trigger: 'blur' }]
          //     }
          //   },
          //   deep: true,
          //   immediate: true
          // }
        },
        mounted() {
          this.$bus.$emit('async_done')
        },
        created() {
          // this.getDictOptions()
        },
        methods: {
          dealTypeChange(val) {
            if (val === 'equity') {
              this.companyLabel = '公司名称'
            } else if (val === 'debt') {
              this.companyLabel = '融资方名称'
            } else if (val === 'bf') {
              this.companyLabel = '基金名称'
            } else if (val === 'estate') {
              this.companyLabel = '项目公司'
            }
            this.$forceUpdate()
          },
          // 项目状态变更
          dealStatusChange(val) {
            if (val === 'CB') {
              this.rules.personCharge = null
            } else {
              this.rules.personCharge = [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
            }
          },
          // 初始化数据
          async init(data) {
              this.loading = true
              this.boundCompanyData.formOpen = false
              await Promise.all(this.getDictOptions())
              if (data !== undefined && data !== null && data.id !== null && data.id !== '' && data.id !== undefined) {
                this.loading = true
                // this.reset()
                getDealBase(data.id).then(response => {
                  this.form = response.data
                  // 储备项目，项目负责人设置为非必填
                  this.dealStatusChange(this.form.dealStatus)
                  this.loading = false
                })
              } else {
                  this.reset(data)
                  this.addTeamPerson()
                  this.loading = false
              }
            },
            // 表单重置
            reset(data) {
              console.log('重置表单')
              this.form = {
                id: undefined,
                dealName: undefined,
                dealNamePinyin: undefined,
                personCharge: this.$store.state.user.userId,
                company: {
                  companyName: '',
                  companyShortName: undefined,
                  industryFirst: undefined,
                  industrySecond: undefined
                },
                dealSource: undefined,
                dateTouchFirst: undefined,
                dateInvestmentEstimate: undefined,
                amountInvestmentEstimate: undefined,
                currency: 'CNY',
                levelConcern: undefined,
                dealIntroduction: undefined,
                dealStrongPoint: undefined,
                dealScruple: undefined,
                dealStatus: undefined,
                companyURL: undefined,
                transactionDetails: undefined,
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined,
                remark: undefined,
                delFlag: undefined,
                // 参股基金字段
                bfBase: {
                  subscribeScale: undefined,
                  paidInScale: undefined,
                  investType: undefined,
                  fundType: undefined,
                  fundTerm: undefined,
                  fundStage: undefined,
                  fundSetTime: undefined,
                  manageCompanyName: '',
                  manageSubscribeRatio: undefined,
                  isReverseInvestment: 'N',
                  targetReverseInvestmentAmount: undefined,
                  reverseInvestmentStandard: undefined
                },
                // 股权项目字段
                dealBaseEquity: {
                  industryFocusList: []
                },
                // 地产项目字段
                dealBaseEstate: {
                  projectLocation: undefined,
                  detailedAddress: undefined,
                  propertyType: undefined,
                  businessType: undefined
                },
                dealBaseProperty: {},
                // 债权项目字段
                dealBaseDebt: {
                  issued: {
                    id: undefined // 发行主体ID
                  }
                },
                dealBaseBond: {},
                fileList: []
              }
              if (data !== undefined && data != null) {
                if (data.dealStatus !== undefined) {
                  this.dealStatusModify = true
                  this.form.dealStatus = data.dealStatus
                  // 储备项目，项目负责人设置为非必填
                  this.dealStatusChange(this.form.dealStatus)
                }
                if (data.dealType !== undefined) {
                  this.dealTypeUpdate = false
                  this.form.dealType = data.dealType
                }
              }
              this.resetForm('form')
            },
            // 关闭form页面
            closeForm() {
              // 关闭form页面遮罩层
              this.loading = false
              // 关闭form页面
              if (this.$parent.$parent.formOpen !== undefined) {
                this.$parent.$parent.formOpen = false
              }
              // 刷新list页面
              if (this.$parent.$parent.getList !== undefined) {
                this.$parent.$parent.getList()
              }
              if (this.$parent.$parent.getViewList !== undefined) {
                this.$parent.$parent.getViewList()
              }
            },
            // 校验数据必填等信息
            validateData: function() {
              return new Promise((resolve, reject) => {
                this.$refs['form'].validate(validTop => {
                  if (validTop) {
                    resolve()
                  } else {
                    reject()
                    this.locationError(document)
                  }
                })
              })
            },
            /** 提交按钮bottom */
            submitForm: function() {
              return new Promise((resolve, reject) => {
                this.validateData().then(() => {
                  this.loading = true
                  saveDealBase(this.form).then(response => {
                    if (response.code === 200) {
                      // 如果在母基金页面新建的项目, 则给这个新建的项目添加一个当前母基金的出资人
                      if (this.$route.query.fundType === 'fof') {
                        const dealInvestor = {
                          dealId: response.data.id,
                          investorId: this.$route.query.id,
                          investorType: 'fund',
                          currency: this.form.currency ? this.form.currency : 'CNY',
                          dateInvestmentEstimate: new Date(),
                          amountInvestmentEstimate: 0
                        }
                        saveDealInvestment(dealInvestor).then(() => {
                          this.closeForm()
                        })
                      }
                      // 如果是通过项目home页面的路由打开，保存时不调用刷新list页面的方法
                      if (this.openLocation === 'Home') {
                        // 项目里边保存
                        this.loading = false
                      }
                      if (this.$parent.$parent.$parent?.formOpen !== undefined) {
                        this.$parent.$parent.$parent.formOpen = false
                        this.$parent.$parent.$parent.init()
                      }
                      this.msgSuccess(this.$t('保存成功'))
                      this.closeForm()
                      resolve()
                    } else {
                      this.msgError(response.msg)
                      this.loading = false
                      reject()
                    }
                  }).catch(() => {
                    this.loading = false
                  })
                }).catch(() => {
                  reject()
                })
              })
           },
          // 标的公司查询
          companyQuerySearch(queryString, cb) {
            if (!this.isEmpty(queryString.trim())) {
              companyListByName(queryString).then(res => {
                if (res.code === 200) {
                  cb(res.data)
                }
              })
            }
          },
          // 标的公司选择后事件
          companyHandleSelect(item) {
            this.form.dealName = this.form.company.companyName
            this.form.company.tycId = item.id
            this.form.company.orgType = item.type
            this.checkDealNameExist()
            this.checkTycAfter(item)
            // 获取改公司下的项目
            this.findDealListByCompanyName(item)
          },
          /**
           * 获取该公司下对应的项目
           * @param data
           */
          findDealListByCompanyName(data) {
            console.log('1', data)
            var _this = this
          _this.boundCompanyData.formOpen = false
            if (data.value !== undefined && data.value !== null && data.value !== '') {
              _this.boundCompanyData.value = data.value
              _this.boundCompanyData.tycId = data.id
              console.log('2', data)
              getCompanyBaseByName({ companyName: data.value, tycId: data.id }).then(response => {
                console.log('3', response)
                const item = response.data
                if (item != null) {
                  if (data.value.trim() === (item.companyName == null ? '' : item.companyName).trim()) {
                    console.log('4', item)
                    // 根据公司Id获取对应的项目
                    _this.initCompanyBoundDeal(item.id)
                  }
                }
              })
            }
          },
          initCompanyBoundDeal(companyId) {
            var _this = this
            findDealBroughtOutCompany({ companyId: companyId, dealType: this.form.dealType }).then(response => {
              if (response.rows !== null && response.rows.length > 0) {
                _this.boundCompanyForm = true
                _this.boundCompanyData.formOpen = true
                _this.$nextTick(() => {
                  _this.$refs.dealBaseBoundCompany.init(response.rows)
                })
              }
            })
          },
          // 判断项目名称是否存在
          checkDealNameExist() {
            const dealName = this.form.dealName
            if (dealName === '' || dealName === undefined) {
              // Notification.error({
              //   title: '请先输入项目名称！！'
              // })
              this.rules.dealName = [{ required: true, message: this.$t('必填信息'), trigger: 'change' }]
              return
            }
            this.tycParam.dealName = dealName

            getDealBaseByName(this.tycParam).then(res => {
              if (res.data !== null && res.data.id !== this.form.id) {
                // Notification.error({
                //   title: '项目名称已存在！！'
                // })
                this.rules.dealName = [{ required: true, message: this.$t('项目名称不能重复'), trigger: 'change' }]
                this.form.dealName = ''
              }
            })
          },
          // 获取天眼查并回显页面结束后执行操作
          checkTycAfter(data) {
            // 地产项目
            if (this.form.dealType === 'estate') {
              console.log('地产项目', data)
            }
          },
          getDictOptions() {
            return [
              // 币种
              this.getDicts('currency').then(response => {
                this.currencyOptions = response.data
              }),
              // 项目类型
              this.getDicts('deal_type').then(response => {
                this.dealTypeOptions = response.data
              }),
              // 项目来源
              this.getDicts('deal_source').then(response => {
                this.dealSourceOptions = response.data
              }),
              // 关注等级
              this.getDicts('level_concern').then(response => {
                this.levelConcernOptions = response.data
              }),
              // 项目阶段
              this.getDicts('deal_stage').then(response => {
                this.dealStageOptions = response.data
              }),
              // 团队成员字典
              this.getDicts('deal_team_role').then(response => {
                this.roleOptions = response.data
              })
            ]
          },
          chartOpenHandle() {
            this.chartOpen = true
            investChartData(this.form.id).then(res => {
              this.chartData = res.data
            })
            this.$nextTick(() => {
              this.$refs.investStructureChart.initCompany({ busId: this.form.company.id, busType: 'company', busName: this.form.company.companyName })
            })
          },
          personChargeChange(personCharge) {
            console.log('项目负责人change: ', personCharge)
            if (this.form) {
              if (personCharge === this.$store.state.user.userId) {
                if (this.form.dealTeamList !== undefined && this.form.dealTeamList !== null) {
                  this.form.dealTeamList.forEach((item, index) => {
                    if (item.disabled && item.role === 'F') {
                      item.user.userId = personCharge
                    }
                    if (item.user.userId === personCharge && item.role !== 'F') {
                      this.form.dealTeamList.splice(index, 1)
                    }
                  })
                }
              } else {
                // 如果项目负责人不是创建人本人, 修改默认添加的项目负责人, 并添加自己为项目成员
                if (this.form.dealTeamList !== undefined && this.form.dealTeamList !== null) {
                  var isExist = false
                  this.form.dealTeamList.forEach((item) => {
                    if (item.disabled && item.role === 'F') {
                      item.user.userId = personCharge
                    }
                    if (item.user.userId === this.$store.state.user.userId && !isExist) {
                      isExist = true
                    }
                  })
                  // 添加自己为项目成员
                  if (!isExist) {
                    this.addTeam({
                      user: { userId: this.$store.state.user.userId },
                      role: 'C',
                      joinTime: new Date(),
                      leave: 'N',
                      disabled: true
                    })
                  }
                }
              }
            }
          },
          delTeam(index) {
            this.form.dealTeamList.splice(index, 1)
          },
          addTeamPerson() {
            this.addTeam({ user: { userId: this.$store.state.user.userId }, role: 'F', joinTime: new Date(), leave: 'N', disabled: true })
          },
          addTeam(data) {
            var row = {
              id: undefined,
              user: { userId: '' },
              role: 'C',
              joinTime: new Date(),
              leave: 'N',
              remark: undefined,
              disabled: false
            }
            if (data !== undefined) {
              row = data
            }
            if (!(this.form.dealTeamList instanceof Array)) {
              this.$set(this.form, 'dealTeamList', [])
            }
            this.$nextTick(() => {
              this.form.dealTeamList.push(row)
            })
          },
          // 提醒设置
          openRemind() {
            this.remindOpen = true
            this.$nextTick(() => {
              this.$refs.remindEvent.init(this.form.id)
            })
          }
        }
    }
</script>

<style scoped>
  .tianyan{
    border: 1px solid #DCDFE6;
    width: 17%;
    border-radius: 5px;
    height: 36px;
    float: right;
    text-align: right;
    padding-right: 15px;
    border-left: 0;
    color: #1E9FFF;
    margin-top: -37px;
    font-size: 13px;
  }
  .right-company-div {
    width: 3rem;
    height: 3rem;
    position: absolute;
    bottom: 52%;
    right: -40px;
    z-index: 1999;
  }
  .right-company-btn {
    width: 30px;
    height: 50px;
    background: orange;
    cursor: pointer;
    border-radius: 100px 0 0 100px;
    line-height: 3.5;
    text-align: center;
    color: white;
  }
</style>
